package nix.anim.sso.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;

import nix.anim.common.pojo.NixResult;
import nix.anim.common.pojo.TreeNode;
import nix.anim.jedis.JedisClient;
import nix.anim.mapper.MenuMapper;
import nix.anim.mapper.UserMapper;
import nix.anim.pojo.Menu;
import nix.anim.pojo.MenuExample;
import nix.anim.pojo.User;
import nix.anim.pojo.UserExample;
import nix.anim.pojo.UserExample.Criteria;
import nix.anim.sso.service.UserService;
import nix.anim.utils.CommonUtils;

/**
 * SSO用户处理Service
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private MenuMapper menuMapper;
	
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${USER_SESSION_KEY}")
	private String USER_SESSION_KEY;
	
	@Value("${USER_SESSION_EXPIRE}")
	private Integer USER_SESSION_EXPIRE;
	
/*	@Value("${SSO_CONSOLE_DOMAIN}")
	private String SSO_CONSOLE_DOMAIN;
	
	@Value("${HOME_CONSOLE_DOMAIN}")
	private String HOME_CONSOLE_DOMAIN;
	
	@Value("${LOG_CONSOLE_DOMAIN}")
	private String LOG_CONSOLE_DOMAIN;
	
	@Value("${CMS_CONSOLE_DOMAIN}")
	private String CMS_CONSOLE_DOMAIN;*/
	
	@Override
	public NixResult login(String username, String password) {
		// 数据校验
		if (StringUtils.isBlank(username)) {
			return NixResult.build(400, "用户名不能为空！");
		}
		if (StringUtils.isBlank(password)) {
			return NixResult.build(400, "密码不能为空！");
		}
		// 查询数据库
		UserExample userExample = new UserExample();
		Criteria criteria = userExample.createCriteria();
		criteria.andUsernameEqualTo(username);
		criteria.andStatusEqualTo(1);
		List<User> userList = userMapper.selectByExample(userExample);
		if (userList == null || userList.size() <= 0) {
			return NixResult.build(400, "用户名不存在！");
		}
		User user = userList.get(0);
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
			return NixResult.build(400, "密码不正确！");
		}
		// 生成token（uuid）
		String token = CommonUtils.uuid();
		// 用户信息保存至Redis
		// 清空密码
		user.setPassword(null);
		jedisClient.set(USER_SESSION_KEY + ":" + token, JSON.toJSONString(user));
		// 设置过期时间
		jedisClient.expire(USER_SESSION_KEY + ":" + token, USER_SESSION_EXPIRE);
		// 返回token
		return NixResult.ok(token);
	}

	@Override
	public NixResult getUserByToken(String token) {		
		// 从Redis获取用户信息
		String json = jedisClient.get(USER_SESSION_KEY + ":" + token);
		if (StringUtils.isBlank(json)) {
			return NixResult.build(400, "用户未登陆或已过期！");
		}
		// 重置key过期时间，保持登陆状态
		jedisClient.expire(USER_SESSION_KEY + ":" + token, USER_SESSION_EXPIRE);
		// 转回pojo再返回，直接返回json会当字符串处理，带转移符
		User user = JSON.parseObject(json, User.class);
		return NixResult.ok(user);
	}

	@Override
	public NixResult logout(String token) {
		// token置过期
		jedisClient.expire(USER_SESSION_KEY + ":" + token, 0);
		return NixResult.ok();
	}

	@Override
	public NixResult getUserById(Integer id) {
		if (id != null) {
			User user = userMapper.selectByPrimaryKey(id);
			if (user != null) {
				return NixResult.ok(user);
			} else {
				return NixResult.build(400, "id不存在！");
			}
		} else {
			return NixResult.build(400, "id无效！");
		}
	}

	@Override
	public NixResult changePassword(String token, String oldPwd, String newPwd) {
		// token验证
		NixResult result = getUserByToken(token);
		if (result.getStatus() != 200) {
			return result;
		}
		// 旧密码验证
		User userRedis = (User) result.getData();
		NixResult result2 = getUserById(userRedis.getId());
		User userCheck = (User) result2.getData();
		if (!DigestUtils.md5DigestAsHex(oldPwd.getBytes()).equals(userCheck.getPassword())) {
			return NixResult.build(400, "旧密码不正确！");
		}
		// 组装pojo（Selective）
		User user = new User();
		user.setId(userCheck.getId());
		user.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
		// 更新
		userMapper.updateByPrimaryKeySelective(user);
		return NixResult.ok();
	}

	@Override
	public NixResult getUserMenuTree(Integer parentId, String token) {
		// token验证
		NixResult result = getUserByToken(token);
		if (result.getStatus() != 200) {
			return result;
		}
		User userRedis = (User) result.getData();
		// 调用递归方法，获得List<TreeNode>
		List<TreeNode> list = getMenuNodesByParentId(parentId, userRedis.getId());
		return NixResult.ok(list);
	}
	
	private List<TreeNode> getMenuNodesByParentId(Integer parentId, Integer userId) {
		List<TreeNode> list = new ArrayList<>();
		// 查询条件：parentId
		MenuExample menuExample = new MenuExample();
		nix.anim.pojo.MenuExample.Criteria criteria = menuExample.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		criteria.andStatusEqualTo(1);
		List<Menu> menuList = new ArrayList<>();
		menuList = menuMapper.selectByExampleUserId(menuExample, userId);
		// 拼接URL
		//menuList = handleMenuURL(menuList);
		// 判断，遍历，组装TreeNode
		if (menuList != null && menuList.size() >= 0) {
			for (Menu menu : menuList) {
				TreeNode node = new TreeNode();
				node.setId(menu.getId());
				node.setName(menu.getName());
				node.setData(menu);
				// 判断：是父节点，则递归子节点
				if (menu.getIsParent()) {
					node.setChildren(getMenuNodesByParentId(menu.getId(), userId));
				}
				list.add(node);
			}
		}
		return list;
	}
	
	/*private List<Menu> handleMenuURL(List<Menu> list) {
		for (Menu menu : list) {
			if (!menu.getIsParent()) {
				switch (menu.getSystem()) {
				case "home":
					menu.setUrl(HOME_CONSOLE_DOMAIN + "#" + menu.getUrl());
					break;
				case "log":
					menu.setUrl(LOG_CONSOLE_DOMAIN + "#" + menu.getUrl());
					break;
				case "cms":
					menu.setUrl(CMS_CONSOLE_DOMAIN + "#" + menu.getUrl());
					break;
				}
			}
		}
		return list;
	}*/

}
